package com.baichuan.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加解密
 */
public class RSAUtils {

    private static final String CHARSET = "UTF-8";
    private static final String RSA_ALGORITHM = "RSA";
    //private static String  PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKuMgd2zEe/67WnqRYGGGb67bOuu0vG79pYSEFX33c6mVHFHU99g91U2bPTyz/9JwugU/S5BTPF0l5bnpAlk3NefsFCXltgtj9s5PZhkOrmu5bRub636Yncsm93Fw9PAiOgmr7jyX8DTRDq3BjKuyJfVxMzPeKtlpazxCRcL6AV5AgMBAAECgYBX0fBRnHBcWCreA85dRlc7qxtRdAgNNFpB7TFrsR5dwgyMiSVIv40elGQm6X7Ng+dBhC0wVsGbAkLwP9lb7cSXzt0xzuyKYMsDdZ/ZPMWVJgU/mfWvG3pKS1fNdq53iWX3rVzf8Dcokux9VVSxojF3l8OEQFoJ3LNBCbD/a74IWQJBAOApjyBE7yLETbcbJ5srmxUx7jr+IIE3vCf2+Ka1/T4xjIabQSEs78k0BaxAA9r5cuiZ1uyZvS18rMcDsJkh988CQQDD6fIhw+YKdsrWLlpJRip2COL5Por6GERG0HF0uo7cVoaPHvkJkESITs4YFNRqZPYQ/eFFFk90oVWGn5Y9Ubg3AkAX6lcqyi/5NZhVAMCo/W3+ROV1xccSAjBA00iUALaT/BVSBx5bu7+ZZ8NzLSE8K4Dm8ALOG1jjkXmdgfdFXyphAkBhNs03hAW6W4f7D7UtduvK9k3qb+Z2g2Qd34Ds80XAgA71JeFdpYDcQn5x5KQix0Zy2AfYSGHU9dmCm93pP4uxAkEAjqQZlhnhmeEgqo9kQL0LANJ7bkZjJHnbIqk5riEQr8Rr0aRWB2MmXbCpnBJuzdORhNEFvhINM6e4DRH+JuBS7Q==";
    //private static RSAPublicKey publicKey;
    //private static RSAPrivateKey privateKey;

    /**
     * 得到公钥
     * @param key 密钥字符串（经过base64编码）
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static RSAPublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));
        return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
    }

    /**
     * 得到私钥
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static RSAPrivateKey getPrivateKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    }

    /**
     * 公钥加密
     * @param data
     * @return
     */
    public static String publicEncrypt(String data, String publicKeyStr){
        try{
            RSAPublicKey publicKey = getPublicKey(publicKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
                   // .replaceAll("\\/", "%2F").replaceAll("\\+", "%2B").replaceAll("\\=", "%3D");
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     * @param data
     * @return
     */
    public static String privateDecrypt(String data, String privateKeyStr){
        try{
            RSAPrivateKey privateKey = getPrivateKey(privateKeyStr);
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }


    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
        int maxBlock = 0;
        if(opmode == Cipher.DECRYPT_MODE){
            maxBlock = keySize / 8;
        }else{
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try{
            while(datas.length > offSet){
                if(datas.length-offSet > maxBlock){
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                }else{
                    buff = cipher.doFinal(datas, offSet, datas.length-offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }

            byte[] resultDatas = out.toByteArray();
            out.close();
            return resultDatas;
        }catch(Exception e){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
    }

    public static void main (String[] args) throws Exception {
        String  PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA4BsLP38l9SUxthVQz9rVIeOWIs771pS4OUAP1dNIzFQ2cx6pttTtHJzYpcmrbEZEIHj7uiwQTo2iciQ+H8NHHQIDAQABAkEAh/lgtcIb8cYDh4sfYT5RmyJPcgdMXkIWFQZ9lSuBPBepNLY/YPDnaLpObjhnSrz1+t33qWTKO/WuSGKTenDGgQIhAP/2i13GM370hz1HtYWmAFo+Rvr5054fyqyXYJ02glJVAiEA4CNSm3EAjkI8wVkkT16RhER9pVYJ4RdntPJFKWPOOakCIGjptunyyTyqIZx+feqPxek3SYSpTZGsWjgvu8v0gaoZAiB8MBYdOkdsixbOqm2L7IIEH07exQVESouTnojjngEtwQIhAIKExWIyurWsyAnqBATGddqKg1SY3FV5l3W+6x2uBeJv";
        String  PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOAbCz9/JfUlMbYVUM/a1SHjliLO+9aUuDlAD9XTSMxUNnMeqbbU7Ryc2KXJq2xGRCB4+7osEE6NonIkPh/DRx0CAwEAAQ==";

        String str = "测试";
        System.out.println("明文：" + str);
        String publicEncrypt = RSAUtils.publicEncrypt(str, PUBLIC_KEY);
        System.out.println("加密结果：" + publicEncrypt);
        String decodedData = RSAUtils.privateDecrypt(publicEncrypt, PRIVATE_KEY);
        System.out.println("解密结果: " + decodedData);
    }
}